package la.ge.server.servlets.repository.uploader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

public class UploadServlet extends HttpServlet {
	
	public UploadServlet() {
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * A servlet to receive a single file upload. 
	 * Note that this servlet assumes a specific part name and creates a 
	 * specific output file, both determined at compile time.
	 * @param request HttpServletRequest
	 * @param response HttpServletResponse
	 * @throws ServletException
	 * @throws IOException
	 */
    public void doPost (HttpServletRequest request,
                        HttpServletResponse response)
                        throws ServletException, IOException {

    	String errorMsg = null;
    	try {
			catchFile( request );
		} catch ( FileUploadException e ) {
			errorMsg = e.getMessage();
		}
    	
        // write the user response
        PrintWriter display = response.getWriter();
        String title = "File Upload";
        response.setContentType("text/html");
        display.println("<html><head><title>" + title + "</title></head>" );
        display.println("<body>");
        display.println("<h1>" + title + "</h1>");
        display.println("<p>FileUpload errorMsg = " + errorMsg + "</p>");
        display.println("</body></html>");
        display.close();
    }
    
    private void catchFile(HttpServletRequest request) throws FileUploadException, IOException {
//   	 Check that we have a file upload request
    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    	if( isMultipart == false ) {
    		throw new IOException( "Not Multipart Content" );
    	}
    	
//    	 Create a factory for disk-based file items
    	FileItemFactory factory = new DiskFileItemFactory();

//    	 Create a new file upload handler
    	ServletFileUpload upload = new ServletFileUpload(factory);

//    	 Parse the request
    	List /* FileItem */ items = upload.parseRequest(request);
    	
    	Iterator iter = items.iterator();
    	while (iter.hasNext()) {
    	    FileItem item = (FileItem) iter.next();

    	    if (item.isFormField()) {
//    	        processFormField(item);
    	    } else {
        	    String fieldName = item.getFieldName();
        	    String fileName = item.getName();
        	    
        	    Matcher m = Pattern.compile( "[^\\\\/\\s]+$" ).matcher( fileName );
        	    if( m.find() ) {
        	    	fileName = m.group();
        	    }
        	    else {
        	    	fileName = System.currentTimeMillis() + ".kml";
        	    }
        	    
        	    String contentType = item.getContentType();
        	    boolean isInMemory = item.isInMemory();
        	    long sizeInBytes = item.getSize();
        	    
        	    try {
					item.write( new File( "./repository/" + fileName ) );
				} catch (Exception e) {
					throw new IOException( e );
				}
        	    
           	    InputStream uploadedStream = item.getInputStream();
           	    
           	    Reader r = new InputStreamReader( uploadedStream );
           	    IOUtils.copy( r, System.out );
           	    r.close();
//        	    ...
        	    uploadedStream.close();
        	    
        	    r = null;
        	    
    	    }
    	}
    	
    }
}
